package com.wxb.controller;

import com.alibaba.fastjson.JSONObject;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.domain.MallAddressEntity;
import com.wxb.service.IMallAddressService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class MallAddressController {
    @Resource
    private IMallAddressService addressService;

    /**
     * 获取用户的收货地址
     */
    @ApiOperation(value = "获取用户的收货地址接口", response = Map.class)
    @PostMapping("list")
    public Object list() {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", SecurityUtils.getUserId());
        List<MallAddressEntity> addressEntities = addressService.queryList(param);
        return AjaxResult.success(addressEntities);
    }

    /**
     * 获取收货地址的详 情
     */
    @GetMapping("detail")
    public Object detail(Integer id) {
        MallAddressEntity entity = addressService.queryObject(id);
        if (null == entity) {
            return AjaxResult.error("地址不存在");
        }
        //判断越权行为
        if (!entity.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error(403, "您无权查看");
        }
        return AjaxResult.success(entity);
    }

    /**
     * 添加或更新收货地址
     */
    @PostMapping("save")
    public Object save() {
        JSONObject addressJson = this.getJsonRequest();
        MallAddressEntity entity = new MallAddressEntity();
        if (null != addressJson) {
            entity.setId(addressJson.getLong("id"));
            entity.setUserId(SecurityUtils.getUserId());
            entity.setUserName(addressJson.getString("userName"));
            entity.setPostalCode(addressJson.getString("postalCode"));
            entity.setProvinceName(addressJson.getString("provinceName"));
            entity.setCityName(addressJson.getString("cityName"));
            entity.setCountyName(addressJson.getString("countyName"));
            entity.setDetailInfo(addressJson.getString("detailInfo"));
            entity.setNationalCode(addressJson.getString("nationalCode"));
            entity.setTelNumber(addressJson.getString("telNumber"));
            entity.setIsDefault(addressJson.getInteger("isDefault"));
        }
        if (null == entity.getId() || entity.getId() == 0) {
            entity.setId(null);
            addressService.save(entity);
        } else {
            addressService.update(entity);
        }
        return AjaxResult.success(entity);
    }

    /**
     * 删除指定的收货地址
     */
    @PostMapping("delete")
    public Object delete() {
        JSONObject jsonParam = this.getJsonRequest();
        Integer id = jsonParam.getIntValue("id");

        MallAddressEntity entity = addressService.queryObject(id);
        //判断越权行为
        if (!entity.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error(403, "您无权删除");
        }
        addressService.delete(id);
        return AjaxResult.success("");
    }


    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
